<template>
  <div class="container-main">
    <ProCard ref="proCard" :columns="searchColumns" :request-api="requestApi" :data-callback="dataCallback">
      <!-- 工具栏左侧 -->
      <template #toolbar-left>
        <el-button type="primary" :icon="Plus" @click="openDrawer('新增')"> 新增 </el-button>
        <el-button v-if="BUTTONS.import" type="primary" :icon="Upload" plain>导入数据</el-button>
        <el-button v-if="BUTTONS.export" type="primary" :icon="Download" plain>导出数据</el-button>
      </template>

      <!-- 卡片头部 -->
      <template #card-header="{ row }">
        <el-tooltip :content="row.name" placement="top">
          <span class="sprint-name">{{ row.name }}</span>
        </el-tooltip>
        <el-tag :type="enumTagRender(row.state, stateOptions)" size="small">
          {{ enumNameRender(row.state, stateOptions) }}
        </el-tag>
      </template>

      <!-- 卡片内容 -->
      <template #card-content="{ row }">
        <div class="sprint-info">
          <div class="info-item">
            <el-icon><Calendar /></el-icon>
            <span>{{ formatDate(row.startDate) }} - {{ formatDate(row.endDate) }}</span>
          </div>
          <div class="info-item">
            <el-icon><Timer /></el-icon>
            <span>研发天数: {{ row.devDays }}天</span>
          </div>
          <div class="info-item">
            <el-icon><User /></el-icon>
            <span>投入人数: {{ row.userCount || 0 }}人</span>
          </div>
          <div class="info-item">
            <el-icon><DataAnalysis /></el-icon>
            <span>投入天数: {{ row.totalDevDays || 0 }}天 (前:{{ row.frontDevDays || 0 }}/后:{{ row.backDevDays || 0 }})</span>
          </div>
          <div class="info-item">
            <el-icon><DataAnalysis /></el-icon>
            <span>需求数量: {{ row.requirementCount || 0 }}个</span>
          </div>
          <div class="info-item">
            <el-icon><Check /></el-icon>
            <span>完成进度: {{ row.progress || 0 }}%</span>
          </div>
        </div>

        <div class="progress-container">
          <el-progress :percentage="row.progress || 0" :show-text="false" />
        </div>
      </template>

      <!-- 卡片底部 -->
      <template #card-footer="{ row }">
        <el-tooltip content="查看" placement="top">
          <el-button type="primary" link :icon="View" @click="openDrawer('查看', row)"></el-button>
        </el-tooltip>
        <el-tooltip content="编辑" placement="top">
          <el-button type="primary" link :icon="Edit" @click="openDrawer('编辑', row)"></el-button>
        </el-tooltip>
        <el-tooltip content="复制" placement="top">
          <el-button type="primary" link :icon="CopyDocument" @click="copySprint(row)"></el-button>
        </el-tooltip>
        <el-tooltip content="删除" placement="top">
          <el-button type="primary" link :icon="Delete" @click="deleteSprint(row)"></el-button>
        </el-tooltip>
      </template>
    </ProCard>

    <!-- 新增/编辑/查看弹窗 -->
    <SprintDrawer ref="drawerRef" />
  </div>
</template>

<script setup lang="ts" name="sprintCard">
import { ref, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";
import {
  Calendar,
  Timer,
  User,
  DataAnalysis,
  Check,
  Plus,
  Upload,
  Download,
  View,
  Edit,
  CopyDocument,
  Delete
} from "@element-plus/icons-vue";
import ProCard from "@/components/ProCard/index.vue";
import SprintDrawer from "./sprintDrawer.vue";
import { useDataStore } from "@/stores/modules/data";
import apiService from "@/api/services/apiService";
import { Sprint } from "./types/sprint";
import { ColumnProps, ProCardInstance } from "@/components/ProCard/interface";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { enumTagRender, enumNameRender } from "@/hooks/useTextRender";
import { useHandleData } from "@/hooks/useHandleData";

const proCard = ref<ProCardInstance>();

// 数据存储
const dataStore = useDataStore();
const { BUTTONS } = useAuthButtons();

// 获取产品列表
const productList = computed(() => dataStore.productList);
const orgList = computed(() => dataStore.orgList);
const stateOptions = computed(() => dataStore.getEnumByCsName("SPRINT_STATE"));
const userList = computed(() => dataStore.userList);

onMounted(() => {
  dataStore.findProductList();
  dataStore.findUserList();
  dataStore.findOrgList();
  dataStore.findEnumByCsName("SPRINT_STATE");
});

// 查询条件配置
const searchColumns = computed(() => {
  const columns: ColumnProps[] = [
    {
      prop: "productIds",
      label: "所属产品",
      enum: productList,
      search: { el: "select", props: { filterable: true } },
      fieldNames: { label: "name", value: "_id" }
    },
    {
      prop: "teamId",
      label: "团队",
      enum: orgList,
      search: { el: "select", props: { filterable: true } },
      fieldNames: { label: "name", value: "_id" }
    },
    {
      prop: "po",
      label: "产品负责人",
      enum: userList,
      search: { el: "select", props: { filterable: true } },
      fieldNames: { label: "userName", value: "_id" }
    },
    {
      prop: "state",
      label: "状态",
      enum: stateOptions,
      search: { el: "select", props: { filterable: true } },
      fieldNames: { label: "name", value: "value" }
    }
  ];
  return columns;
});

// 请求API
const requestApi = async (params: any) => {
  // 获取冲刺主表数据
  const result = await apiService.findPage<Sprint.Sprint>("sprint", params.condition, params.options);

  // 为每个冲刺获取相关的用户和需求数量
  if (result.data && result.data.content) {
    const content = result.data.content;

    // 获取所有冲刺ID
    const sprintIds = content.map(sprint => sprint._id).filter((id): id is string => Boolean(id));

    if (sprintIds.length > 0) {
      // 批量查询用户信息
      try {
        const userRes = await apiService.find<any[]>("sprint_user", { sprintId: { $in: sprintIds } }, false);
        const userCounts: Record<string, number> = {};
        const userDevDays: Record<string, { front: number; back: number; total: number }> = {};
        if (userRes.data) {
          userRes.data.forEach(user => {
            userCounts[user.sprintId] = (userCounts[user.sprintId] || 0) + 1;
            if (!userDevDays[user.sprintId]) {
              userDevDays[user.sprintId] = { front: 0, back: 0, total: 0 };
            }
            userDevDays[user.sprintId].front += user.type === "0" ? user.devDays || 0 : 0;
            userDevDays[user.sprintId].back += user.type === "1" ? user.devDays || 0 : 0;
            userDevDays[user.sprintId].total += user.devDays || 0;
          });
        }

        // 批量查询需求数量和状态
        const reqRes = await apiService.find<any[]>("user_requirement", { sprintId: { $in: sprintIds } }, false);
        const reqCounts: Record<string, number> = {};
        const reqCompletedCounts: Record<string, number> = {};
        if (reqRes.data) {
          reqRes.data.forEach(req => {
            reqCounts[req.sprintId] = (reqCounts[req.sprintId] || 0) + 1;
            // 状态为"2"表示已完成
            if (req.state === "2") {
              reqCompletedCounts[req.sprintId] = (reqCompletedCounts[req.sprintId] || 0) + 1;
            }
          });
        }

        // 将统计结果合并到冲刺数据中
        content.forEach(sprint => {
          sprint.userCount = (sprint._id && userCounts[sprint._id]) || 0;
          sprint.requirementCount = (sprint._id && reqCounts[sprint._id]) || 0;

          // 计算前端和后端投入天数
          if (sprint._id && userDevDays[sprint._id]) {
            sprint.frontDevDays = userDevDays[sprint._id].front;
            sprint.backDevDays = userDevDays[sprint._id].back;
            sprint.totalDevDays = userDevDays[sprint._id].total;
          } else {
            sprint.frontDevDays = 0;
            sprint.backDevDays = 0;
            sprint.totalDevDays = 0;
          }

          // 计算完成进度
          if (sprint._id && reqCounts[sprint._id] > 0) {
            const completed = reqCompletedCounts[sprint._id] || 0;
            sprint.progress = Math.round((completed / reqCounts[sprint._id]) * 100);
          } else {
            sprint.progress = 0;
          }
        });
      } catch (error) {
        console.error("批量查询用户和需求数量失败:", error);
        // 出错时设置默认值
        content.forEach(sprint => {
          sprint.userCount = 0;
          sprint.requirementCount = 0;
          sprint.frontDevDays = 0;
          sprint.backDevDays = 0;
          sprint.totalDevDays = 0;
          sprint.progress = 0;
        });
      }
    } else {
      // 没有有效的冲刺ID时设置默认值
      content.forEach(sprint => {
        sprint.userCount = 0;
        sprint.requirementCount = 0;
        sprint.frontDevDays = 0;
        sprint.backDevDays = 0;
        sprint.totalDevDays = 0;
        sprint.progress = 0;
      });
    }
  }

  return result;
};

// 数据回调处理
const dataCallback = (data: any) => {
  return data;
};

// 格式化日期
const formatDate = (date: Date | string) => {
  if (!date) return "";
  return new Date(date).toLocaleDateString();
};

// 删除冲刺
const deleteSprint = async (sprint: any) => {
  try {
    await useHandleData(apiService.deleteById, "sprint", sprint._id || "", `删除冲刺【${sprint.name}】`);
    // 刷新卡片列表
    proCard.value?.refresh();
  } catch (error) {
    console.error("删除失败:", error);
  }
};

// 复制冲刺
const copySprint = async (sprint: any) => {
  try {
    // 创建一个新的冲刺对象，排除_id属性
    const newSprint = { ...sprint };
    delete newSprint._id;

    // 重新设置创建人和创建时间
    newSprint.create_by = undefined; // 让后端重新设置创建人
    newSprint.create_at = undefined; // 让后端重新设置创建时间

    // 在冲刺名称前添加[复制]标记
    if (newSprint.name && !newSprint.name.startsWith("[复制]")) {
      newSprint.name = `[复制]${newSprint.name}`;
    }

    // 先保存新的冲刺主表数据
    const res: any = await apiService.save("sprint", newSprint, false);
    const newSprintId = res.data._id;

    // 获取原冲刺的用户数据
    const userRes = await apiService.find<any[]>("sprint_user", { sprintId: sprint._id }, false);

    // 复制用户数据到新的冲刺
    if (userRes.data && userRes.data.length > 0) {
      const newUserList = userRes.data.map(user => {
        // 创建新的用户数据，替换sprintId为新的ID
        return {
          ...user,
          _id: undefined, // 清除原来的_id
          sprintId: newSprintId // 设置新的sprintId
        };
      });

      // 保存新的用户数据
      await apiService.saveList("sprint_user", newUserList);
      proCard.value?.refresh();
    }

    // 打开新增抽屉，显示复制后的数据
    openDrawer("编辑", { ...newSprint, _id: newSprintId });

    ElMessage.success("冲刺复制成功");
  } catch (error) {
    console.error("复制冲刺失败:", error);
    ElMessage.error("冲刺复制失败");
  }
};

// 打开抽屉(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof SprintDrawer> | null>(null);
const openDrawer = (title: string, row: Partial<Sprint.Sprint> = {}) => {
  const params = {
    title,
    tbName: "sprint",
    isView: title === "查看",
    row: { ...row },
    api: title === "新增" ? apiService.save : title === "编辑" ? apiService.updateById : undefined,
    getTableList: proCard.value?.refresh
  };
  drawerRef.value?.acceptParams(params);
};
</script>

<style lang="scss" scoped>
.container-main {
  .sprint-name {
    display: inline-block;
    max-width: 80%;
    overflow: hidden;
    font-size: 16px;
    font-weight: bold;
    text-overflow: ellipsis;
    white-space: nowrap;
    vertical-align: middle;
  }
  .sprint-info {
    .info-item {
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      font-size: 14px;
      .el-icon {
        margin-right: 8px;
        color: var(--el-color-primary);
      }
    }
  }
  .progress-container {
    margin-top: 15px;
  }
}
</style>
